// BaziFragment.java
package com.bhcj.telling.view.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bhcj.telling.R;
import com.bhcj.telling.model.bean.BaziInfo;
import com.bhcj.telling.utils.BaziCalculator;

/**
 * 四柱八字功能的 Fragment
 * 用于在ViewPager2中展示生辰八字排盘界面
 */
public class BaziFragment extends Fragment {

    private EditText editYear, editMonth, editDay, editHour;
    private Button btnCalculate;
    private TextView tvResult;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_bazi, container, false);
        initViews(inflate);
        setListeners();
        return inflate;
    }


    private void initViews(View view) {
        editYear = view.findViewById(R.id.edit_year);
        editMonth = view.findViewById(R.id.edit_month);
        editDay = view.findViewById(R.id.edit_day);
        editHour = view.findViewById(R.id.edit_hour);
        btnCalculate = view.findViewById(R.id.btn_calculate);
        tvResult = view.findViewById(R.id.tv_result);
    }

    private void setListeners() {
        btnCalculate.setOnClickListener(v -> calculateBazi());
    }

    private void calculateBazi() {
        try {
            int year = Integer.parseInt(editYear.getText().toString());
            int month = Integer.parseInt(editMonth.getText().toString());
            int day = Integer.parseInt(editDay.getText().toString());
            int hour = Integer.parseInt(editHour.getText().toString());

            BaziInfo info = BaziCalculator.calculate(year, month, day, hour);
            displayResult(info);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "请输入有效的日期时间", Toast.LENGTH_SHORT).show();
        }
    }

    private void displayResult(BaziInfo info) {
        StringBuilder result = new StringBuilder();

        result.append("【四柱八字】\n");
        result.append("年柱：").append(info.getYearPillar()).append("\n");
        result.append("月柱：").append(info.getMonthPillar()).append("\n");
        result.append("日柱：").append(info.getDayPillar()).append("\n");
        result.append("时柱：").append(info.getHourPillar()).append("\n\n");

        result.append("【五行分析】\n");
        result.append(info.getElementAnalysis()).append("\n\n");

        result.append("【十神分析】\n");
        result.append(info.getTenGodAnalysis()).append("\n\n");

        result.append("【大运走势】\n");
        result.append(info.getLuckCycleTrend());

        tvResult.setText(result.toString());
    }
}
